package com.shuoyue.adven.main.bussiness;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.danikula.videocache.HttpProxyCacheServer;
import com.dueeeke.videoplayer.ijk.IjkPlayerFactory;
import com.dueeeke.videoplayer.player.VideoView;
import com.dueeeke.videoplayer.util.L;
import com.shuoyue.adven.CommonUtil;
import com.shuoyue.adven.Constant;
import com.shuoyue.adven.R;
import com.shuoyue.adven.SpacesItemDecoration;
import com.shuoyue.adven.cache.ProxyVideoCacheManager;
import com.shuoyue.adven.entity.Adv;
import com.shuoyue.adven.entity.ImpotentResult;
import com.shuoyue.adven.entity.Property;
import com.sm.appbase.base.basemvp.BaseMvpFragment;
import com.sm.appbase.net.exception.NetErrorException;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class FragmentBusiness extends BaseMvpFragment<MainContract.Presenter> implements MainContract.View {
    @BindView(R.id.m_data)
    RecyclerView mDataRecyclerView;
    @BindView(R.id.big_img)
    ImageView bigImg;
    @BindView(R.id.player)
    VideoView mVideoView;
    @BindView(R.id.imgs_pager)
    public ViewPager imgsPager;
    private BusinessDataAdapter adapter;
    private Handler handler;
    //    Handler handler;
    private LinearLayoutManager linearLayoutManager;
    private int lastShowDialogPosititon = -1;//上一个放大展示的位置，用于判断是否已经展示过
    private Runnable scrolltask;
    private Runnable netTask;
    private Runnable importentTask;
    private Runnable pagerScrollTask;
    private Runnable bigImgTask;

    //    protected List<Adv> mGalleryAdapter.getMedias() = new ArrayList<>();
    public PropertyAdapter mGalleryAdapter;
    int playTimes;


    ImpotentResult impotentResult;//插屏广告信息

    @Override
    public void initParams(Bundle bundle) {

    }

    @Override
    public void initData() {
        mPresenter = new MainContract.Presenter();
        mPresenter.attachView(this);
        initTimerTask();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        mVideoView.setEnableAudioFocus(false);
        mVideoView.addOnStateChangeListener(mOnStateChangeListener);
        //初始化滚动控件
        linearLayoutManager = new LinearLayoutManager(mContext);
        mDataRecyclerView.setLayoutManager(linearLayoutManager);
        mDataRecyclerView.addItemDecoration(new SpacesItemDecoration(CommonUtil.dip2px(mContext, 24), false));
//        int width = getViewWidth(mDataRecyclerView);
        adapter = new BusinessDataAdapter(mContext, null);
        mDataRecyclerView.setAdapter(adapter);
        //初始化小屏
//        showScreen2();
        //初始化插屏广告
        mGalleryAdapter = new PropertyAdapter(mContext, null);
        imgsPager.setAdapter(mGalleryAdapter);
        mGalleryAdapter.setImgScaleType(ImageView.ScaleType.CENTER_INSIDE);
        imgsPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                if (mGalleryAdapter.getMedias().size() == 0)
                    return;

                Adv adv = mGalleryAdapter.getMedias().get(position % mGalleryAdapter.getMedias().size());
                uploadShowInfo(adv.getId());
                if (adv.getType() == adv.TYPE_VIDEO) {
                    playVideo(adv.getVideoUrl(), 1, 2);
                    handler.removeCallbacks(pagerScrollTask);
                } else {
                    mVideoView.setVisibility(View.GONE);
                    mVideoView.release();
                }
                if ((impotentResult.getAdPositionInfo().getSwitch_num() == 0 ?
                        position >= mGalleryAdapter.getMedias().size()
                        : position >= mGalleryAdapter.getMedias().size() * impotentResult.getAdPositionInfo().getSwitch_num())
                        && (impotentResult.getAdPositionInfo().getShowModel() == 1
                        || impotentResult.getAdPositionInfo().getShowModel() == 3)) {
                    stopCurrent();
                    startScroll();

                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mDataRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }


    void initTimerTask() {
        handler = new Handler();
        netTask = () -> {
            handler.postDelayed(netTask, Constant.NET_TASK * 1000);
            Log.e("任务：", "网络任务");
            doNetTask();
        };
        scrolltask = () -> {
            handler.postDelayed(scrolltask, 1000 / Constant.main_SCROLL_FRAM);//设置延迟时间
            //需要执行的代码
//            Log.e("任务：", "滚动任务");
            doScrollTask();
        };
        importentTask = () -> {
            handler.postDelayed(importentTask,
                    impotentResult == null || impotentResult.getAdPositionInfo().getSwitch_second() == 0
                            ? Constant.IMPOTENT_CHECK * 1000 : impotentResult.getAdPositionInfo().getSwitch_second() * 1000);//60 * 1000 * 10);
            Log.e("任务：", "插屏广告监测任务");
            if (impotentResult != null
                    && impotentResult.getList() != null
                    && impotentResult.getList().size() > 0
                    && impotentResult.getAdPositionInfo().getShowModel() != 3) {
                if (imgsPager.getVisibility() == View.GONE) {
                    startCurrent();
                }
            }
        };

        pagerScrollTask = () -> {
            handler.postDelayed(pagerScrollTask, Constant.IMPOTENT_SCROLL_DELAY);//Constant.SUB_SCREEN_SCROLL_DELAY
            Log.e("任务：", "切屏任务");
            imgsPager.setCurrentItem(imgsPager.getCurrentItem() + 1);
        };
        bigImgTask = () -> {
            Log.e("任务：", "大图任务");
            if (bigImg != null) {
                bigImg.setVisibility(View.INVISIBLE);
                startScroll();
            }
        };

        handler.postDelayed(scrolltask, 2000);//初始化的时候延迟2秒滚动，给第一个展示时间
        handler.post(netTask);
        handler.post(importentTask);
    }

    /**
     * 每次滚动后执行的任务
     */
    void doScrollTask() {
        mDataRecyclerView.scrollBy(0, Constant.MAIN_SCROLL_SPEED);
//        int firstPos = linearLayoutManager.findFirstVisibleItemPosition();
        int lastPos = linearLayoutManager.findLastCompletelyVisibleItemPosition();
        if (lastShowDialogPosititon != lastPos && lastPos > -1) {
            lastShowDialogPosititon = lastPos;
            Adv adv = adapter.getMDatas().get(lastPos % adapter.getMDatas().size());
            //位置变化到新的一个，可以尝试打开Image或者视频
            if (adv.getType() == adv.TYPE_IMG) {
                if (Constant.IS_CAN_OPEN_BIG_IMG) {
                    stopScroll();
                    bigImg.setVisibility(View.VISIBLE);
                    if (!getActivity().isFinishing()) {
                        Glide.with(mContext)
                                .load(adv.getImgUrl())
                                .error(R.mipmap.img_loading_gray)
                                .placeholder(R.mipmap.img_loading_gray)
                                .into(bigImg);
                    }
                    stopShowImgDelay(adv.getImgShowMills());
                }
            } else if (adv.getType() == adv.TYPE_VIDEO) {
                playVideo(adv.getVideoUrl(), 1, 1);
            }
            //上报展现通知
            uploadShowInfo(adv.getId());
        }
//        checkNumState();
    }

    void doNetTask() {
        mPresenter.queryBusinessAdv();
        mPresenter.queryImpotentAdv();
        mPresenter.queryPropertyAdv();
        mPresenter.getPropertyInfo();
    }


    /**
     * 开启滚动
     */
    void startScroll() {
        handler.postDelayed(scrolltask, 1000 / Constant.main_SCROLL_FRAM);//滚动
    }

    /**
     * 停止滚动
     */
    void stopScroll() {
        handler.removeCallbacks(scrolltask);
    }


    void startCurrent() {
        if (impotentResult != null && impotentResult.getList() != null) {
            handler.removeCallbacks(bigImgTask);
            bigImg.setVisibility(View.GONE);
            stopScroll();
            imgsPager.setVisibility(View.VISIBLE);
            mGalleryAdapter = new PropertyAdapter(mContext, impotentResult.getList());
            imgsPager.setAdapter(mGalleryAdapter);
            handler.postDelayed(pagerScrollTask, Constant.SUB_SCREEN_SCROLL_DELAY);
        }
    }

    void stopCurrent() {
        imgsPager.setVisibility(View.GONE);
        handler.removeCallbacks(pagerScrollTask);
        startScroll();
    }

    /**
     * 定时隐藏大图
     */
    void stopShowImgDelay(long timeMills) {
        handler.postDelayed(bigImgTask, timeMills == 0 ? Constant.BIG_IMG_SHOW_TIME_SCENDS : timeMills);//延迟调用
    }

    int playType = 1;//1滚屏视频、2插屏视频

    void playVideo(String url, int times, int playType) {
        Log.e("播放视频", url + ";" + playType);
        mVideoView.release();
        this.playType = playType;
        stopScroll();
        this.playTimes = times;
        mVideoView.setVisibility(View.VISIBLE);
        HttpProxyCacheServer cacheServer = ProxyVideoCacheManager.getProxy(mContext);
        String proxyUrl = cacheServer.getProxyUrl(url);
        mVideoView.setUrl(proxyUrl);
        mVideoView.setPlayerFactory(IjkPlayerFactory.create());
        mVideoView.start();

    }

    void onKeyBackPressLisenter() {
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                    if (mVideoView.getVisibility() == View.VISIBLE) {
                        mVideoView.release();
                        mVideoView.setVisibility(View.GONE);
                        startScroll();
                        return true;
                    } else
                        return false;
                }

                return false;
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mVideoView != null) {
            mVideoView.resume();
        }

        handler.removeCallbacks(scrolltask);
        startScroll();
    }


    @Override
    public void onPause() {
        super.onPause();
        if (mVideoView != null) {
            mVideoView.pause();
        }
        stopScroll();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mVideoView != null) {
            mVideoView.release();
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }


    }


    @Override
    public void queryBusinessAdvSuc(List<Adv> mData) {
        if (adapter.getMDatas() == null || adapter.getMDatas().size() == 0) {
            adapter.resetData(mData);
            adapter.notifyDataSetChanged();
        } else {
            if (adapter.getMDatas() != null && !MatchUtils.isSame(adapter.getMDatas(), mData)) {
                adapter.resetData(mData);
                adapter.notifyDataSetChanged();
            }
        }
        checkScrollState2();

    }

    @Override
    public void queryPropertyAdvSuc(List<Adv> mdata) {

    }

    @Override
    public void queryImpotentAdvSuc(ImpotentResult mdata) {
        impotentResult = mdata;
        mGalleryAdapter.resetData(mdata.getList());
    }

    @Override
    public void getPropertyInfoSuc(Property property) {

    }

    private VideoView.OnStateChangeListener mOnStateChangeListener = new VideoView.SimpleOnStateChangeListener() {
        @Override
        public void onPlayerStateChanged(int playerState) {
            switch (playerState) {
                case VideoView.PLAYER_NORMAL://小屏
                    break;
                case VideoView.PLAYER_FULL_SCREEN://全屏
                    break;
            }
        }

        @Override
        public void onPlayStateChanged(int playState) {
            Log.e("播放状态", playState + "");
            switch (playState) {

                case VideoView.STATE_PREPARING:
                    //在STATE_PREPARING时设置setMute(true)可实现静音播放
//                    mVideoView.setMute(true);
                    break;
                case VideoView.STATE_PREPARED:
                    break;
                case VideoView.STATE_PLAYING:
                    //需在此时获取视频宽高
                    int[] videoSize = mVideoView.getVideoSize();
                    L.d("视频宽：" + videoSize[0]);
                    L.d("视频高：" + videoSize[1]);
                    break;
                case VideoView.STATE_PAUSED:
                    break;
                case VideoView.STATE_BUFFERING:
                    break;
                case VideoView.STATE_BUFFERED:
                    break;
                case VideoView.STATE_IDLE:
                case VideoView.STATE_PLAYBACK_COMPLETED:
                case VideoView.STATE_ERROR:
//                    if (playTimes <= 1) {
                    mVideoView.release();
                    mVideoView.setVisibility(View.GONE);
                    if (playType == 1) {
                        startScroll();
                        //滚动播放完毕
                        //1隐藏空间
                        //2开始滚动
                        mVideoView.setVisibility(View.GONE);
                        mVideoView.release();
                        handler.post(scrolltask);
                    } else {
                        mVideoView.setVisibility(View.GONE);
                        mVideoView.release();
                        handler.post(pagerScrollTask);
                    }
                    break;
            }
        }
    };

    @Override
    public void onError(NetErrorException throwable) {
        super.onError(throwable);
//        Toast.makeText(mContext, throwable.getMessage(), Toast.LENGTH_SHORT).show();
    }

    public void uploadShowInfo(int id) {
        mPresenter.uploadShow(id);
    }

    private void checkScrollState2() {
        if (adapter.getMDatas() == null || adapter.getMDatas().size() == 0) {
            adapter.notifyDataSetChanged();
            return;
        }
        boolean canScroll = false;//滚动标记
        // 1.查看是否有重复
        List<Adv> advsShowing = new ArrayList<>();
        int firstPos = linearLayoutManager.findFirstVisibleItemPosition();
        int lastPos = linearLayoutManager.findLastVisibleItemPosition();
        if(firstPos == -1|| lastPos == -1){
            return;
        }
        Adv advFirst = null;
        for (int i = firstPos; i <= lastPos; i++) {

            Adv adv = adapter.getMDatas().get(i % adapter.getMDatas().size());
            if (i == firstPos) {
                advFirst = adv;
            }
            advsShowing.add(adv);
        }
        boolean isHasSame = false;
        for (int i = 1; i < advsShowing.size(); i++) {
            Adv a = advsShowing.get(i);
            if (a.getId() == advFirst.getId()) {
                isHasSame = true;
                break;
            }
        }
        if (!isHasSame) {
            //没有重复
            //对比当前的几个的高度是否大于容器高度
            int sumHeight = 0;
            for (int i = firstPos; i <= lastPos; i++) {
                View view = mDataRecyclerView.getLayoutManager().findViewByPosition(i);
                if (view != null)
                    sumHeight += view.getHeight() + CommonUtil.dip2px(mContext, 24);
            }
            int layoutHeight = getContentView().getHeight();
            if (sumHeight + CommonUtil.dip2px(mContext, 24) > layoutHeight) {
//                Log.e("滚动检查", "元素高度大于了");
                canScroll = true;
            }
        }
        if (adapter.needScroll != canScroll) {
            Log.e("滚动检查", "是否需要滚动发生了转变:old" + adapter.needScroll + ",now:" + canScroll);
            adapter.setNeedScroll(canScroll);
            adapter.notifyDataSetChanged();
        }

    }

}

